package com.stp.event.util;

import cn.hutool.core.lang.tree.Tree;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class TreeUtils {
	public static final String ID = "id";
	public static final String PARENT_ID = "parentId";
	public static final String EXTRA = "extra";
	public static final String CHILDREN = "children";

	public static List<Tree> listToTree(List<?> dataList){
		return listToTree(dataList,ID,PARENT_ID,CHILDREN);
	}

	/**
	 * list转为树状结构
	 *
	 * @param dataList 需要转化的数据
	 * @param id       数据唯一的标识键值
	 * @param parentId      父id唯一标识键值
	 * @param children    子节点键值
	 * @param <?>      参数类型实体
	 * @return List
	 */
	public static List<Tree> listToTree(List<?> dataList, String id, String parentId, String children) {
		if (CollectionUtils.isEmpty(dataList)) {
			return new ArrayList<>();
		}
		JSONArray arr = JSONArray.parseArray(JSON.toJSONString(dataList));
		JSONArray result = new JSONArray();
		JSONObject dataObject = new JSONObject();
		// 将数组转为Object的形式，key为数组中的id
		for (int i = 0; i < arr.size(); i++) {
			JSONObject json = arr.getJSONObject(i);
			if(json.containsKey(TreeUtils.EXTRA)){
				json.putAll(json.getJSONObject(TreeUtils.EXTRA));
				json.remove(TreeUtils.EXTRA);
			}
			dataObject.put(json.getString(id), json);
		}
		for (int i = 0; i < arr.size(); i++) {
			JSONObject data = arr.getJSONObject(i);
			// 获取父节点
			JSONObject parentObject = dataObject.getJSONObject(data.getString(parentId));
			// 如果记录的pid存在，则说明它有父节点，将数据添加到父节点的子节点集合中
			if (parentObject == null) {
				result.add(data);
			} else {
				//检查是否有child属性
				JSONArray childList = parentObject.getJSONArray(children);
				if (childList == null) {
					childList = new JSONArray();
					childList.add(data);
					parentObject.put(children, childList);
				} else {
					childList.add(data);
				}
			}
		}
		return JSON.parseArray(result.toJSONString(), Tree.class);
	}

}
